import React from 'react';
import Taro from '@tarojs/taro';

import {connect} from 'react-redux';
import * as T from './types';
import actions from './actions';
import {store2Props} from './selectors';

import {View, Button, Image} from '@tarojs/components';
import ResultModal from './components/ResultModal/ResultModal';
import {
  GAME_SHARE_TITLE,
  OSS_BASE_PATH_PREFIX,
  TASK_CONDITION_TYPE,
  CODE_SUCCESS,
  SYNTHETCI_SELECT_PROP_STORE,
  SYNTHETCI_SELECT_TASK,
  NAVBAR_TITLE,
} from './constant';

import './index.less';
import 'taro-ui/dist/style/components/flex.scss';

actions().actions.loadReducer();

// @ts-ignore
@connect<Partial<T.IProps>, any>(store2Props, actions)
export default class SyntheticDrawCardPa extends React.Component<Partial<T.IProps>, any> {
  // 使用state值
  constructor(props) {
    super(props);
    this.state = {
      query: {}, // 路径中携带参数

      // 随机配置
      animation: {
        max: 9, // 最多9个
        speed: 300, // 循环速度
        isEnd: false,
      },

      items: [], // 卡牌列表
      selectIndex: 0,
      timer: null,

      gameStart: false,

      // 模态框配置
      modal: {
        visible: false,
      },
      pics: {
        gameShareIcon: OSS_BASE_PATH_PREFIX + '/gameShareIcon.png', // 分享至朋友圈
        gameShareThum: OSS_BASE_PATH_PREFIX + '/gameShareThum.png', // 分享缩略图
      },

      navbarSettings: {
        navBarHeight: 0, // 导航栏高度
        menuRight: 0, // 胶囊距右方间距（方保持左、右间距一致）
        menuTop: 0, // 胶囊距底部间距（保持底部间距一致）
        menuHeight: 0, // 胶囊高度（自定义内容可与胶囊高度保证一致）
      },
    };
  }

  componentDidShow() {
    this.handleGetRouterParams(); // 获取路由参数
    this.handleRandomItems(); // 随机卡牌
    this.props.actions.init();
  }

  componentDidMount(): void {
    this.getNavHeight();
  }

  /**
   * 获取navbar高度
   */
  getNavHeight() {
    var sysinfo = Taro.getSystemInfoSync();
    const menuButtonInfo = Taro.getMenuButtonBoundingClientRect();
    let navBarHeight = sysinfo.statusBarHeight + 44;
    let menuRight = sysinfo.screenWidth - menuButtonInfo.right;
    let menuTop = menuButtonInfo.top;
    let menuHeight = menuButtonInfo.height;
    this.setState({
      navbarSettings: {
        ...this.state.navbarSettings,
        navBarHeight, // 导航栏高度
        menuHeight,
        menuTop,
      },
    });
  }

  componentWillReceiveProps(nextProps: Readonly<Partial<T.IProps>>, nextContext: any): void {
    console.log(
      'index.tsx nextProps',
      nextProps.main.status.loadingIsNewComer,
      'this.props',
      this.props.main.status.loadingIsNewComer,
    );
    // 抽卡结束
    if (nextProps.main.status.loadingGameLottery === false && this.props.main.status.loadingGameLottery == true) {
      console.log('抽卡查询结束');
      this.setState({
        gameStart: false,
      });
      this.setState({
        animation: {
          ...this.state.animation,
          isEnd: true,
        },
      });
      let query = Taro.getStorageSync(SYNTHETCI_SELECT_TASK);
      if (nextProps.main.response.gameLottery == CODE_SUCCESS) {
        if (query.taskConditionsType == TASK_CONDITION_TYPE['game']) {
          if (query && query.taskId) {
            this.handleComputedTask(query);
          }
        }
      }
    }

    // 是否是新人返回再调用接口开始循环排
    if (nextProps.main.status.loadingIsNewComer === false && this.props.main.status.loadingIsNewComer == true) {
      this.handleStartDrawCard(); // 开始循环排
      setTimeout(() => {
        this.handleQueryGameLottery(); // 开始查询抽奖结果
      }, 2000);
    }

    // 做任务
    if (nextProps.main.status.computingTask == false && this.props.main.status.computingTask == true) {
      let success = nextProps.main.response.computedTask == CODE_SUCCESS ? true : false;
      Taro.showToast({
        title: success ? '任务完成' : '任务失败',
        icon: 'none',
      });
    }
  }

  componentWillUnmount() {
    this.props.actions.clean();

    // 清除定时器
    this.handleClearSetInterval();
  }

  /**
   * 清除定时器
   */
  handleClearSetInterval = () => {
    let {timer} = this.state;
    clearInterval(timer);
    this.setState({
      timer: null,
      selectId: null,
    });
  };

  /**
   * 获取路由参数
   */
  handleGetRouterParams = () => {
    let params = Taro.getCurrentInstance()?.router?.params;
    console.log('syntheticDrawCard handleGetRouterParams params', params);
    // 收藏进来的就直接去首页
    if (params.favorite) {
      Taro.redirectTo({
        url: '/pages/package-I/home/index',
      });
      return;
    }

    this.handleQueryIsNewComer();

    // 使用道具
    let selectProp = Taro.getStorageSync(SYNTHETCI_SELECT_PROP_STORE);
    params.selectProp = selectProp || {};

    this.setState({
      query: params,
    });
  };

  /**
   * 完成任务
   */
  handleComputedTask = (data) => {
    let params = {
      id: data.taskId,
    };
    console.log('syntheticDrawCard handleComputedTask params', params);
    this.props.actions.action.computedTask(params);
  };

  /**
   * 查询是否是新人保障
   */
  handleQueryIsNewComer = () => {
    console.log('新人新人');
    let params = {};
    this.props.actions.action.loadUserIsNewComer(params);
  };

  /**
   * 随机卡牌
   */
  handleRandomItems = () => {
    const {animation} = this.state;

    let items = [];
    for (let i = 0; i < animation.max; i++) {
      items.push({
        id: 'card' + i,
        key: i,
      });
    }

    this.setState({
      items,
    });
  };

  /**
   * 抽奖
   */
  handleQueryGameLottery = () => {
    const {query} = this.state;
    console.log('index.tsx handleQueryGameLottery query', query);

    let params = {
      ipId: query.id,
      lotteryCount: query.count,
    };

    console.log('handleQueryGameLottery query', query);

    // 如果有道具的话
    if (query && query.selectProp && query.selectProp.id) {
      params.propId = query.selectProp.propId;
      params.myPropId = query.selectProp.id;
    }
    console.log('index.tsx handleQueryGameLottery params', params);

    this.props.actions.action.gameLottery(params);
  };

  /**
   * 开始抽牌
   */
  handleStartDrawCard = () => {
    console.log('开始抽牌');

    let {timer, animation} = this.state;

    if (timer) return;

    // 开始旋转下标
    let idx = -1;
    // 当前旋转圈数
    let num = 0;

    // 旋转圈数Math.floor(Math.random() * (max - min + 1)) + min;
    const random = 10; // 保守估计5圈，后台返回就立即结束

    // 停留目标
    // const target = Math.ceil(Math.random() * 9) - 1;

    timer = setInterval(() => {
      idx++;
      if (idx > 8) {
        idx = 0;
        num++; // 累计圈数
      }

      console.log('index.tsx animation.isEnd', this.state.animation.isEnd);

      // 后台有反馈就结束
      if (this.state.animation.isEnd) {
        console.log('animation.isEnd', animation.isEnd);
        clearInterval(timer);
        timer = null;

        this.setState({
          gameStart: false,
        });

        // 成功则弹出结果页面
        if (this.props.main.response.gameLottery == CODE_SUCCESS) {
          this.setState({
            modal: {
              visible: true,
            },
          });
          Taro.removeStorageSync(SYNTHETCI_SELECT_TASK); // 删除任务
          Taro.removeStorageSync(SYNTHETCI_SELECT_PROP_STORE); // 删除选择道具
        } else {
          return;
        }
      }

      // 没有等到后台返回，就定个最大值
      else {
        this.setState({
          gameStart: true,
        });
        // console.log('index.tsx num', num, 'random', random);
        // if (num >= random) {
        //   clearInterval(timer);
        //   timer = null;
        //   this.setState({
        //     modal: {
        //       visible: true,
        //     },
        //   });
        // }
      }
      this.setState({
        selectIndex: idx,
        timer,
      });
    }, animation.speed);
  };

  /**
   * 再来一次
   */
  handlePlayAgin = () => {
    this.setState({
      selectIndex: null,
      modal: {
        visible: false,
      },
    });
    // 跳转到收集卡页面
    Taro.redirectTo({
      url: '/pages/package-I/syntheticCard/index?reset=true',
    });
  };

  /**
   * 渲染
   * @returns
   */
  render() {
    if (!this.props.main) return null;
    let {
      main: {isLoading, userInfo},
    } = this.props;
    console.log(isLoading);
    const {
      animation,
      items,
      selectIndex,
      modal: {visible},
      query,
      navbarSettings,
    } = this.state;
    console.log('index.tsx render animation=', items);
    console.log('index.tsx render animation', animation);

    console.log('index.tsx render selectindex', selectIndex);

    return (
      <View className="pageSyntheticDrawCardPa" catchMove>
        {this.renderNavBar()}
        <View className="cardItems">
          {this.renderCardItems(selectIndex, items)}
          {userInfo.isNewComer && !animation.isEnd ? <View className="gameExtra">新人加成生效中</View> : <></>}
        </View>
        <ResultModal
          query={query}
          onPlayAgain={this.handlePlayAgin}
          visible={visible}
          onCancel={this.handleCancel}
          navbarSettings={navbarSettings}
        />
      </View>
    );
  }

  /**
   * 渲染基本信息
   */
  renderNavBar() {
    const {
      navbarSettings: {navBarHeight, menuHeight, menuTop},
      gameStart,
    } = this.state;

    console.log('index.tsx renderNavBar gameStart', gameStart);
    return (
      <View className="navHeader">
        <View className="navbar" style={{height: navBarHeight}}>
          <View style={{height: menuHeight, top: menuTop}} className="navBarContent">
            {!gameStart && <View className="at-icon at-icon-chevron-left" onClick={this.handleNavBack}></View>}
            <View className="navTitle" style={{fontSize: '36rpx'}}>
              {NAVBAR_TITLE}
            </View>
          </View>
        </View>
      </View>
    );
  }

  /**
   * 渲染卡片
   * @param items
   * @returns
   */
  renderCardItems(selectIndex, items) {
    const {
      navbarSettings: {navBarHeight},
    } = this.state;
    return (
      <View className="at-row at-row--wrap at-row__justify--around">
        {items.map((i: any, index: number) => (
          <View className="at-col at-col-4" key={'card' + index}>
            <View className={selectIndex == index ? 'item' : 'activeItem'}></View>
          </View>
        ))}
      </View>
    );
  }

  /**
   * 点击返回
   */
  handleNavBack = () => {
    Taro.navigateBack();
  };

  /**
   * 取消
   */
  handleCancel = () => {
    this.setState({
      modal: {
        visible: false,
      },
    });
  };

  /**
   * 收藏
   * @param res
   * @returns
   */
  onAddToFavorites(res) {
    const {
      pics: {gameShareIcon},
    } = this.state;

    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target);
    }
    return {
      title: GAME_SHARE_TITLE,
      imageUrl: gameShareIcon,
      query: 'favorite=true',
    };
  }
}
